package com.yckj.ytracker.api.util;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

public class IdGenerator {

    private static AtomicInteger count = new AtomicInteger(1024);

    /**
     * get traceId by localIP + timeStamp + count
     */
//    public static String createTraceIdByLocalIp() {
//        return getId(InetAddressUtil.getLocalIpHex(), System.currentTimeMillis(), getNextId());
//    }

    /**
     * get traceId by IP + timeStamp + count
     *
     * @param ip input IP
     */
//    public static String createTraceIdByIp(String ip) {
//        if ((ip != null) && (!(ip.isEmpty())) && (InetAddressUtil.validate(ip))) {
//            return getId(InetAddressUtil.IpToHex(ip), System.currentTimeMillis(), getNextId());
//        }
//        return createTraceIdByLocalIp();
//    }

    /**
     * get TraceId by UUID
     */
    public static String createTraceId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * get Span id 初始值
     */
    public static int newSpanId() {
        return 0;
    }

    private static String getId(String ip, long timestamp, int nextId) {
        return ip + timestamp + nextId;
    }

    private static int getNextId() {
        while (true) {
            int current = count.get();
            int next = (current > 8192) ? 1024 : current + 1;
            if (count.compareAndSet(current, next)) {
                return next;
            }
        }
    }
}
